package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func readFromFile1() {
	fileObj, err := os.Open("./main.go")
	if err != nil {
		fmt.Printf("open file failed,err:%v \n", err)
	}

	//记得关闭文件
	defer fileObj.Close()
	//读文件
	//自定读的长度
	//var tmp = make([]byte, 128)
	var tmp [128]byte
	for {
		n, err := fileObj.Read(tmp[:])
		if err == io.EOF {
			fmt.Println("读完了")
			return
		}
		if err != nil {
			fmt.Printf("read from file failed,err:%v \n", err)
			return
		}
		if n < 128 {
			return
		}
		fmt.Printf("读了%d个字节 \n", n)
		fmt.Println(string(tmp[:n]))
	}
}

func readFromFilebybufio() {
	fileObj, err := os.Open("./main.go")
	if err != nil {
		fmt.Printf("open file failed,err:%v \n", err)
	}

	//记得关闭文件
	defer fileObj.Close()
	//创建一个用来从文件中读内容的对象
	reader := bufio.NewReader(fileObj)
	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Println("读完了")
			return
		}
		if err != nil {
			fmt.Printf("read line failed,err:%v\n", err)
		}

		fmt.Println(line)
	}
}

func readFromFileByioutil() {
	ret, err := ioutil.ReadFile("./main.go")
	if err != nil {
		fmt.Printf("read file failed,err：%v\n", err)
	}
	fmt.Println(string(ret))

}
func main() {
	//readFromFile1() //按照字节数读取
	//readFromFilebybufio()  //一行一行读取
	readFromFileByioutil() //一次性全部读取
}
